package top.v5it.logback.push.channel.weixin;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import top.v5it.logback.push.channel.ChannelPushStrategy;
import top.v5it.logback.push.channel.LogInfo;
import top.v5it.logback.push.channel.VoidFunc;
import top.v5it.logback.push.util.StringTemplateUtil;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 企业徾信推送
 *
 * @author zhanpu
 * @date 2022/9/7
 */
public class WeiXinChannelPushStrategy implements ChannelPushStrategy {

    @Override
    public <E> boolean push(Map<String, Object> pushConfig, byte[] payload, VoidFunc failedCallback) {
        final LogInfo logInfo = getLogInfo(payload);
        // 拼装at联系人
        final String url = MapUtil.getStr(pushConfig, "server.url");
        final int timeout = MapUtil.getInt(pushConfig, "server.timeout");
        final String contactsStr = MapUtil.getStr(pushConfig, "contacts");
        final boolean isAtAll = MapUtil.getBool(pushConfig, "atAll", Boolean.TRUE);
        final List<String> contacts = StrUtil.splitTrim(contactsStr, ",");
        // 拼装at联系人
        String atStr = contacts.stream()
                .map(v -> StrUtil.format("<@{}>", v))
                .collect(Collectors.joining());
        // 在内容中添加at
        String content = StringTemplateUtil.markdown(logInfo.getMessage().getTitle()
                , getLevel(pushConfig, logInfo.getLevel())
                , logInfo.getTimestamp()
                , logInfo.getLogger()
                , logInfo.getMessage().getDescription().replace("\\n", "\n"));
        content += "\n> " + atStr;
        content = isAtAll ? content + "<@all>" : content;
        // 设置发送内容
        WeiXinRobotSendRequest.Markdown markdown = new WeiXinRobotSendRequest
                .Markdown()
                .setContent(content);
        // 设置请求参数
        WeiXinRobotSendRequest request = new WeiXinRobotSendRequest()
                .setMsgtype(WeiXinRobotSendRequest.MsgtypeEnum.markdown)
                .setMarkdown(markdown);
        try {
            WeiXinUtil.asyncSend(url, request, timeout, t -> {
                if (!t.isOk()) {
                    failedCallback.call();
                    return;
                }
                WeiXinRobotSendResponse response = JSONUtil.toBean(t.body(), WeiXinRobotSendResponse.class);
                if (response.getErrcode().compareTo(0) == 0) return;
                failedCallback.call();
            });
            return true;
        } catch (Exception e) {
            failedCallback.call();
            return false;
        }
    }
}
